import {StyleSheet, Text, TouchableOpacity, View, ScrollView, Image, TextInput} from 'react-native'
import React, {useEffect, useState} from 'react'
import PageScrollView from "@/components/PageScrollView";
import PageTabBar from "@/components/PageTabBar";
import NoData from "@/components/NoData";
import FcButton from "@/components/FcButton";
import FcModal from '@/components/FcModal';
import useGetStorage from "@/hooks/useGetStorage";
import {Flex, Toast} from "@ant-design/react-native";;
import {LinearGradient} from "expo-linear-gradient";
import * as ImagePicker from "expo-image-picker";

import {
  useGetFeedbackListQuery,
} from "@/store/api/home/homeApi";

import {
  useFeedbackAddMutation,
} from "@/store/api/my/myApi";

type Props = {}

const feedback = (props: Props) => {
  const [listParams, setListParams] = useState({
    pageNo: 1,
    pageSize: 20,
  })
  const [userInfo, setUserInfo] = useState<any>({})
  const [module, setModule] = useState('')
  const [description, setDescription] = useState('')
  const [phone, setPhone] = useState('')
  const [imgList, setImgList] = useState<any>([])
  const [feedbackList, setFeedbackList] = useState<any>([])
  const [progressOpen, setProgressOpen] = useState<any>(false)

  const {data:listDataRef,isSuccess:listSuccess,refetch:listRefetch} = useGetFeedbackListQuery(listParams)
  const [feedbackAddFun] = useFeedbackAddMutation()

  useEffect(() => {
    useGetStorage('userInfo').then(res => {
      setUserInfo(res.userInfo)
    })
    listRefetch()
  },[])

  useEffect(() => {
    if(listDataRef?.code === 200){
      const list = listDataRef?.result?.records || []
      setFeedbackList(list)
    }
  },[listDataRef, listSuccess])

  //上传
  async function uploadFile() {
    let permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();

    if (permissionResult.granted === false) {
      alert('Permission to access gallery is required!');
      return;
    }

    let pickerResult = await ImagePicker.launchImageLibraryAsync({
      allowsMultipleSelection: true, //可以在相册中选择多个
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: false, // 可选，允许用户编辑所选图片或视频。
      quality: 1, // 可选，设置图片或视频的质量。0到1之间。1表示最高质量。
    });

    if (!pickerResult.canceled) {
      let arr = imgList.concat(pickerResult?.assets)
      setImgList(arr)
    }
  }

  //删除图片
  const handleDeleteImg = (index:any) => {
    let arr = JSON.parse(JSON.stringify(imgList))
    arr.splice(index, 1)
    setImgList(arr)
  }

  //提交反馈
  const handleSubmit = async() => {
    if(!module || !description) return
 
    let formData = new FormData();
    // formData.append('module', ['AI内容创作', 'AI找爆款'].join().replace(/,/g, '-'));
    formData.append('module', module);
    formData.append('description', description);
    formData.append('phone', phone);

    for(let i in imgList){
      formData.append('images', {
        uri: imgList[i].uri,
        type: 'image/jpeg',
        name: imgList[i].fileName,
      });
    }
  
    feedbackAddFun(formData).then(res => {
      listRefetch()
      Toast.info('提交成功')
    })
  }

  return (
    <PageScrollView
      isTransparentTab
      pageTab={
        <PageTabBar
          style={{marginVertical: 10}}
          title={'意见反馈'}
          right={
            <TouchableOpacity style={{display: 'flex', flexDirection: 'row', alignItems: 'center'}} onPress={() => setProgressOpen(true)}>
              <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#000000', marginRight: 3}}>&#xe67a;</Text>
            </TouchableOpacity>
          }
        />
      }
      pageBottom={
        <Flex justify='center' style={{height: 56, backgroundColor: '#FFF'}}>
          {
            <FcButton
              onClick={() => handleSubmit()}
              type='BjJB'
              colors={description && module ? ['#6989FF', '#C65EFD'] : ['rgba(105,137,255,0.4)', 'rgba(198,94,253,0.4)']}
              style={{width: '90%', height: 40, justifyContent: 'center'}}
              itemStyle={{borderRadius: 8, fontSize: 15}}
              textName='提交'
            />
          }
        </Flex>
      }
    >
      <View style={styles.feedback_box}>
        <Flex>
          <Text style={{color: 'rgba(0, 0, 0, 0.5)'}}>用户账号：</Text>
          <Text>{userInfo.realname}</Text>
        </Flex>

        <View style={{marginTop: 20}}>
          <Text>所属模块 <Text style={{color: '#FA5151'}}>*</Text></Text>
          {/* <TouchableOpacity onPress={() => router.push("/my/moduleSelect")}>
            <View style={styles.item_wrap}>
              <Text style={[false ? styles.item_label : styles.item_hint]}>
                {false || '请选择'}
                </Text>
              <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: 'rgba(0, 0, 0, 0.3)'}}>&#xe609;</Text>
            </View>
          </TouchableOpacity> */}
          <TextInput
            style={[styles.desc_input, {height: 56, lineHeight: 16}]}
            multiline={true}
            value={module}
            placeholderTextColor={'rgba(0, 0, 0, 0.3)'}
            placeholder={'请输入所属模块'}
            onChangeText={(val) => {setModule(val)}}
          />
        </View>

        <View style={{marginTop: 20}}>
          <Text>问题描述 <Text style={{color: '#FA5151'}}>*</Text></Text>
          <TextInput
            style={[styles.desc_input, {height: 250}]}
            multiline={true}
            value={description}
            placeholderTextColor={'rgba(0, 0, 0, 0.3)'}
            placeholder={'请详细描述反馈的具体内容、问题出现的场景、期望的解决方案等'}
            onChangeText={(val) => {if(description.length <= 500) setDescription(val)}}
          />
          <Text style={{position: 'absolute', bottom: 15, right: 12, color: 'rgba(0, 0, 0, 0.3)'}}>{description.length || 0}/500</Text>
        </View>

        <View style={{marginTop: 20}}>
          <Text>附件</Text>
          {
            imgList.length == 0 ?
            <TouchableOpacity style={{height: 56, marginTop: 10}} onPress={() => uploadFile()}>
              <LinearGradient
                colors={['#6989FF', '#C65EFD']}
                style={styles.gradientBorder}
                start={{x: 0, y: 0}}
                end={{x: 1, y: 1}}
              >
                <LinearGradient
                  style={styles.innerBox}
                  colors={['rgba(105, 137, 255, 0.1)', 'rgba(198, 94, 253, 0.1)']}
                  start={{x: 0, y: 0}}
                  end={{x: 1, y: 1}}
                >
                  <Flex style={{height: '100%'}} justify='center' align='center'>
                    <Image style={{width: 22, height: 22}} resizeMode={'contaicn'} source={require('@/assets/images/add.png')}></Image>
                    <Text style={{color: '#334DB0', marginLeft: 5}}>点击上传</Text>
                  </Flex>
                </LinearGradient>
              </LinearGradient>
            </TouchableOpacity>
            :
            <ScrollView
              horizontal
              showsHorizontalScrollIndicator={false}
              contentContainerStyle={{paddingTop: 10}}
            >
              <Flex>
                <TouchableOpacity style={{width: 56, height: 56}} onPress={() => uploadFile()}>
                  <LinearGradient
                    colors={['#6989FF', '#C65EFD']}
                    style={styles.gradientBorder}
                    start={{x: 0, y: 0}}
                    end={{x: 1, y: 1}}
                  >
                    <LinearGradient
                      style={styles.innerBox}
                      colors={['rgba(105, 137, 255, 0.1)', 'rgba(198, 94, 253, 0.1)']}
                      start={{x: 0, y: 0}}
                      end={{x: 1, y: 1}}
                    >
                      <Flex style={{height: '100%'}} justify='center' align='center'>
                        <Image style={{width: 22, height: 22}} resizeMode={'contain'} source={require('@/assets/images/add.png')}></Image>
                      </Flex>
                    </LinearGradient>
                  </LinearGradient>
                </TouchableOpacity>
                {
                  imgList.map((item:any, index:any) => (
                    <View key={index}>
                      <Image style={styles.img_item} resizeMode={'cover'} source={{uri: item.uri}}></Image>
                      <TouchableOpacity key={index} style={styles.close_btn} onPress={() => handleDeleteImg(index)}>
                        <Text style={{fontFamily: 'FcIconFont', fontSize: 10, color: '#FFF'}}>&#xe61a;</Text>
                      </TouchableOpacity>
                    </View>
                    
                  ))
                }
              </Flex>
            </ScrollView>
          }
        </View>

        <View style={{marginTop: 20}}>
          <Text>联系方式</Text>
          <TextInput
            style={[styles.desc_input, {height: 56, lineHeight: 16}]}
            multiline={true}
            value={phone}
            placeholderTextColor={'rgba(0, 0, 0, 0.3)'}
            placeholder={'请输入手机号'}
            onChangeText={(val) => {setPhone(val)}}
          />
        </View>
      </View>

      {/* 进度查询弹窗 */}
      <FcModal
        isOpen={progressOpen}
        onFcModalClose={() => setProgressOpen(false)}
        titleText='进度查询'
        titleBottomBorderWidth={1}
      >
        <View style={{paddingHorizontal: 16, paddingVertical: 12}}>
          {
            feedbackList.map((item:any, index:any) => (
              <View key={index} style={styles.feedback_item}>
                <Text numberOfLines={2}>{item.description}</Text>
                <Flex justify='between' style={{marginTop: 10}}>
                  <Text style={styles.feedback_item_date}>{item.createTime}</Text>
                  <Text style={item.status == -1 ? styles.feedback_BH : item.status == 2 ? styles.feedback_CG : styles.feedback_CL}>
                    {item.status == -1 ? '已驳回' : item.status == 2 ? '已处理' : item.status == 0 ? '待处理' : '处理中'}
                  </Text>
                </Flex>
                {
                  item.status == -1 ? 
                  <View style={styles.reason}>
                    <Text><Text style={{color: 'rgba(0, 0, 0, 0.5)'}}>驳回原因：</Text>{item.reason}</Text>
                  </View>
                  : null
                }
              </View>
            ))
          }
          {feedbackList.length == 0 && <Flex><NoData hintText='暂无数据'/></Flex>}
        </View>
      </FcModal>
    </PageScrollView>
  )
}

export default feedback

const styles = StyleSheet.create({
  feedback_box: {
    padding: 12,
    borderRadius: 8,
    backgroundColor: '#FFF',
  },
  item_wrap: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: 'space-between',
    height: 56,
    paddingHorizontal: 12,
    backgroundColor: '#F1F2F4',
    borderRadius: 8,
    marginTop: 10,
  },
  item_label: {
    fontSize: 17,
    color: 'rgba(0,0,0,0.9)'
  },
  item_hint: {
    fontSize: 17,
    color: 'rgba(0,0,0,0.3)'
  },
  desc_input: {
    backgroundColor: '#F1F2F4',
    color: 'rgba(0,0,0,0.9)',
    fontSize: 15,
    lineHeight: 26,
    paddingTop: 20,
    paddingBottom: 8,
    paddingHorizontal: 12,
    borderRadius: 8,
    marginTop: 10,
  },
  gradientBorder: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    borderWidth: 1,
    borderStyle: 'dashed',
    borderRadius: 8,
    borderColor: 'transparent',
  },
  innerBox: {
    height: '100%',
    width: '100%',
    backgroundColor: 'white',
    borderRadius: 8,
  },
  img_item: {
    width: 56,
    height: 56,
    borderRadius: 8,
    marginLeft: 8,
  },
  close_btn: {
    width: 15,
    height: 15,
    borderRadius: 8,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    position: 'absolute',
    top: -6,
    right: -6,
  },
  feedback_item: {
    padding: 12,
    borderRadius: 8,
    backgroundColor: '#F1F2F4',
    marginBottom: 8,
  },
  feedback_item_date: {
    fontSize: 12,
    color: 'rgba(0, 0, 0, 0.15)',
  },
  feedback_BH: {
    width: 68,
    height: 30,
    color: '#FA5151',
    borderRadius: 8,
    textAlign: 'center',
    lineHeight: 30,
    backgroundColor: 'rgba(250, 81, 81, 0.1)',
  },
  feedback_CG: {
    width: 68,
    height: 30,
    color: '#29CCA0',
    borderRadius: 8,
    textAlign: 'center',
    lineHeight: 30,
    backgroundColor: 'rgba(41, 204,160 , 0.1)',
  },
  feedback_CL: {
    width: 68,
    height: 30,
    color: '#FF9D00',
    borderRadius: 8,
    textAlign: 'center',
    lineHeight: 30,
    backgroundColor: 'rgba(255, 157, 0, 0.1)',
  },
  reason: {
    borderTopWidth: 1,
    borderStyle: 'dashed',
    borderColor: '#D8D8D8',
    marginTop: 15,
    paddingTop: 10,
  }
})

